package com.mezz.bones.framework.excel.demo;

import cn.hutool.core.util.StrUtil;
import cn.idev.excel.EasyExcel;
import cn.idev.excel.ExcelWriter;
import cn.idev.excel.support.ExcelTypeEnum;
import cn.idev.excel.write.metadata.WriteSheet;
import com.google.common.net.HttpHeaders;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class ExcelFileTemplateImportService {

    /**
     * 使用Excel模板导出数据（支持单个对象和多个列表数据）
     * @param fileName 导出文件名（含后缀）
     * @param response Http响应对象
     * @param templateInputStream Excel模板输入流
     * @param singleObjectData 要填充的单个对象数据（可为null）
     * @param listDataMap 要填充的列表数据Map（key为模板中的列表名称，value为数据列表）
     */
    public void exportWithExcelTemplate(String fileName,
                                        HttpServletResponse response,
                                        InputStream templateInputStream,
                                        Object singleObjectData,
                                        Map<String, List<?>> listDataMap) {
        // 参数校验
        if (StrUtil.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        if (templateInputStream == null) {
            throw new IllegalArgumentException("模板输入流不能为空");
        }

        ExcelWriter excelWriter = null;
        try (ServletOutputStream outputStream = response.getOutputStream();
             InputStream inputStream = templateInputStream) {

            // 设置响应头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

            // 创建Excel写入器
            excelWriter = EasyExcel.write(outputStream)
                    .withTemplate(inputStream)
                    .excelType(ExcelTypeEnum.XLS)
                    .build();

            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            // 填充单个对象数据
            if (singleObjectData != null) {
                excelWriter.fill(singleObjectData, writeSheet);
            }

            // 填充列表数据
            if (MapUtils.isNotEmpty(listDataMap)) {
                ExcelWriter finalExcelWriter = excelWriter;
                listDataMap.forEach((listName, dataList) -> {
                    if (CollectionUtils.isNotEmpty(dataList)) {
                        finalExcelWriter.fill(dataList,
                                EasyExcel.writerSheet().needHead(Boolean.FALSE).build());
                    }
                });
            }

        } catch (IOException e) {
            throw new RuntimeException("Excel导出失败", e);
        } finally {
            // 确保资源关闭
            if (excelWriter != null) {
                excelWriter.finish();
            }
            IOUtils.closeQuietly(templateInputStream);
        }
    }

}
